<!DOCTYPE HTML>
<html>
<head>
    <meta charset="utf-8">
    <title>首页</title>

    <script type="text/javascript">
        function connect() {
            if ("WebSocket" in window) {
               // alert("您的浏览器支持 WebSocket!");
                var username = document.getElementById("from").value;
                // 打开一个 web socket
                ws = new WebSocket("ws://"+location.host+"/websocket/" + username);

                ws.onopen = function () {

                    // alert("数据发送中...");
                    fillData("建立连接了")
                };

                ws.onmessage = function (evt) {
                    var received_msg = evt.data;
                    fillData(received_msg);
                };

                ws.onclose = function () {
                    // 关闭 websocket
                    fillData("关闭连接了")
                };
            } else {
                // 浏览器不支持 WebSocket
                alert("您的浏览器不支持 WebSocket!");
            }
        }

        function fillData(data) {
            document.getElementById("content").innerHTML = data;
        }

        function send() {
            var from =document.getElementById("from").value;
            var to =document.getElementById("to").value;
            var msg =document.getElementById("msg").value;
            var message='{"from":"'+from+'","to":"'+to+'","content":"'+msg+'"}'
           // alert(message);
            ws.send(message);
        }
    </script>


</head>
<body>

用户名:<input id="from">
<button onclick="connect()">连接</button><br>
<br>
<br>
<br>
接收者:<input id="to"><br>
<br>
<br>
内容:<textarea id="msg"></textarea><br>
<br>
<br>

<button onclick="send()">发送</button><br>
<br>


<span id="content"></span>
</body>
</html>